package com.itgo.codegen.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

import com.itgo.codegen.config.Config;

public class DbHelper {

	private static Connection connection ;
	
	public static Connection getConnection(){
		try{
			if( connection != null && !connection.isClosed() ){
				return connection ;
			}
			Class.forName( Config.driverPath ) ;
			connection = DriverManager.getConnection(
					Config.jdbcUrl , Config.dbUserName , Config.dbPassword ) ;
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
		return connection ;
	}
	
	public static void close( Object ... objs  ){
		if( objs == null || objs.length == 0 ){
			return ;
		}
		for( Object obj : objs ){
			try{
				if( obj instanceof Connection ){
					((Connection) obj).close();
				}
				if( obj instanceof Statement ){
					((Statement)obj).close() ;
				}
				if( obj instanceof PreparedStatement ){
					((PreparedStatement)obj).close() ;
				}
				if( obj instanceof ResultSet ){
					((ResultSet)obj).close() ;
				}
			}catch(Exception e){
				
			}
		}
	}
	
	public static <T> List<T> queryList ( String sql , Class<T> clazz , Object ...objects ){
		Connection conn = getConnection() ;
		PreparedStatement pstm = null ;
		List<T> results = new ArrayList<T>() ;
		ResultSet result = null ;
		try{
			pstm = conn.prepareStatement( sql ) ;
			if( objects != null && objects.length > 0 ){
				for( int idx = 1 ; idx <= objects.length ; idx ++  ){
					pstm.setObject( idx , objects[idx - 1 ] );
				}
			}
			result = pstm.executeQuery() ;
			ResultSetMetaData metaData = result.getMetaData() ;
			for( int i = 0 ; i < metaData.getColumnCount() ; i ++ ){
				String column = metaData.getColumnName(i+1) +";"+
						metaData.getColumnTypeName(i+1) + ";" +
						metaData.getColumnDisplaySize(i+1) +";" +
						metaData.getScale(i+1);
				System.out.println( column );
			}
			while( result.next() ){
				T item = clazz.newInstance() ;
				int count = metaData.getColumnCount();
				for( int i = 1 ; i <= count ; i ++ ){
					String fieldName = StringLang.tfRule( metaData.getColumnName( i ) ) ;
					if( clazz.getDeclaredField( fieldName ) == null ){
						continue ;
					}
					BeanUtils.setProperty(
							item , fieldName , result.getString(metaData.getColumnName( i ) ) );
				}
				results.add( item ) ;
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			close( result , conn , pstm ) ;
		}
		return results ;
	}
}
